package com.chase.flashcleaner.utils

import android.app.AlertDialog
import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.widget.Toast
import java.io.PrintWriter
import java.io.StringWriter

fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) =
    Toast.makeText(this, text, duration).show()

fun Context.showAlert(
    message: String,
    positive: String,
    negative: String,
    positiveAction: (dialog: DialogInterface) -> Unit = {},
    negativeAction: (dialog: DialogInterface) -> Unit = {}
) {
    val dialogOnClickListener = DialogInterface.OnClickListener { dialog, which ->
        when (which) {
            Dialog.BUTTON_POSITIVE -> positiveAction(dialog)
            Dialog.BUTTON_NEGATIVE -> negativeAction(dialog)
        }
    }
    val alertBuilder = AlertDialog.Builder(this)
    alertBuilder.setMessage(message)
    alertBuilder.setPositiveButton(positive, dialogOnClickListener)
    alertBuilder.setNegativeButton(negative, dialogOnClickListener)
    alertBuilder.create().show()
}

fun logd(message: String, functionName: String = "", contextName: String = "") =
    Log.d("GSC-$functionName-$contextName", message)

fun copy2Clipboard(context: Context, data: String) {
    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    // Set data into clipboard
    clipboard.primaryClip = ClipData.newPlainText(null, data)
}

fun Exception.getContent(): String {
    val sw = StringWriter()
    val pw = PrintWriter(sw, true)
    this.printStackTrace(pw)
    pw.flush()
    sw.flush()
    return sw.toString()
}